<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="com.google.appengine.api.users.User" %>
<%@ page import="com.google.appengine.api.users.UserService" %>
<%@ page import="com.google.appengine.api.users.UserServiceFactory" %>
<%@ page import="info.niwota.webagent.peer.ChannelManager" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hotweb Proxy</title>
<base target="_self" >
<link rel="icon" type="image/ico" href="/assets/image/favicon.ico" >
<link rel="stylesheet" href="/assets/style/common.css" type="text/css" >
<link rel="stylesheet" href="/assets/style/custom.css" type="text/css" >
<style type="text/css">
.wrapper { 
	margin-top: 32px;
	margin-bottom: auto;
	margin-left: 32px;
	margin-right: 32px;
	width: 800px; 
	text-align: left; 
	border: none; 
	clear: both;
}

.section-title {
	padding-left: 8px; 
	padding-right: 8px; 
	font-size: large;
	clear: both;
	text-align: left; 
}

.section {
	padding-left: 8px; 
	padding-right: 8px; 
	clear: both;
	text-align: left; 
}
</style>
<script type="text/javascript" src="https://www.google.com/jsapi?key=ABQIAAAAk4kw-fYBzjizex9DHmmuXBSSoBz1sb4nFR_F9xgzOIXLsu5DxhRLXs9wmoRrDDngUCMjbQ7tSNBeBg"></script>
<!-- failed to load randomly src="/_ah/channel/jsapi" -->
<script type="text/javascript" src="http://talkgadget.google.com/talkgadget/channel.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script type="text/javascript" src="/assets/script/common.js"></script>

<script type="text/javascript">
var spinner = '<img src="/assets/image/spin.gif" alt="Please wait..." style="color: #fff;"><span style="color: #fff; font-size: xx-large;">...<blink>.....</blink></span>';

$.ajaxSetup ({  
	cache: false  
}); 

function showBusy(timeout, msg) {
	var tag = $('#status');
	
	var t = timeout || 3000;
	var m = msg || '';
	tag.html(spinner);
	var timer = setTimeout(function(){ tag.html(m).css({ "color": "#ff0000" }); }, t);
	
	this.cancel = function() {
		clearTimeout(timer);
		tag.empty();
	}
	
	return this;
}

function loadHome() {
	//load template and show; data is pre-loaded
	//$('#page-content').html(spinner).load('/web/home.htmf', function () {
	//	showHome(data);
	//});
}

$(document).ready(function(){
	$.fullScreen();
	
	loadHome();
	//
	$('a.ajax').live('click', function() {
		var link = $(this).attr('href');
    	$('#page-content').html(spinner).load(link);
    	return false;
	});
	//
	$.initOptionMenu();
	//$.disableContextMenu();
	//	
	
	initEmail();
	
	initChannel();
});
</script>
<script type="text/javascript">
var emailaddress_pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
<%
	Object data = ChannelManager.getInstance().createChannel(request);
%>
var data = <%= data %>;

function isValidEmailAddress(s) {
	var email = $.trim(s);
    if (email.length == 0) {
      return false;
	}
	return emailaddress_pattern.test(email);
}

function initEmail() {
var input = '#peer';
var hint = input+'_hint';

$(input).keyup(function(){
  var email = $(input).val();
  if(email) {
    if(isValidEmailAddress(email)) {
       $(hint).html('&#10004;').css({ "color": "#00ff00" });
    } else {
       $(hint).html('&#10006;').css({ "color": "#ff0000" });
    } 
  } else {
    $(hint).html('').css({ "color": "#ffffff" });
  }
});
}

function doSubmit(f) {
	var pid = f.peer.value;
	if(!isValidEmailAddress(pid)) {
		return false;
	}
	//
	var url = '/redirect?peer='+ pid + '&cid=' + data.cid;
	
	var busy = showBusy(5000, 'Timeout, please try again.');
	
	$.getJSON(url, function(d) {
		busy.cancel();
		
		var tag = $('#status');
 		if (d && d.error) {
			tag.html(d.error).css({ "color": "#ff0000" });
		} else {
			tag.empty();
		}
	});

	return false;
}

function initChannel() {
	if (data && data.token) {
		openChannel();
		return;
	}
		
	$.getJSON('/channel', function(d) {
		if (d) {
			if (d.token) {
				data = d;
				openChannel();
			} else if (d.error) {
				showError(d.error);
			}
		}
	});
}

function showError(s) {
	$('#status').html(s).css({ "color": "#ff0000" });
}

function openChannel() {
	var ch = new goog.appengine.Channel(data.token);
	var handler = {
		'onopen':  function() {},
		'onmessage': function(m) {
			var res = JSON.parse(m.data);
			if (res) {
				redirectHome(res.ip, res.port, res.peer);
			}
		},
		'onerror': function() {
			showError('Failed');
		},
		'onclose': function() {}
	};
	
	ch.open(handler);
}

function redirectHome(ip, port, peer) {
	var url = 'http://' + ip + ':' + port + '/home';
	var err = 'Peer '+ peer +' not responding/not reachable at: ' + url;
	var busy = showBusy(5000, err);
	
	$.getJSON(url + '?type=json&callback=?', function(d) {
		busy.cancel();
		
		if (d && d.jid == peer) {
			window.location.replace(url);
		} else {
			showError(err);
		}
	});
	return false;
}

function loadScript(src) {
	var s = document.createElement('script');
	s.type = 'text/javascript';
	s.src = src;
	$('head').append(s);
}
</script>
</head>
<body >

<div id="topnav">
	<a class="logo" href="/" title="Access your phone from a browser.">
	<img class="icon32" src="/assets/image/favicon.png"  alt="Proxy" >
	<span>Proxy</span>
	</a>

	<span class="top-right" style="margin-right: 64px;">
	<span class="action" id="userid">
<%
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
if (user != null) {
%>
<%= user.getNickname() %>
<%
}
%>
	</span>&nbsp;&nbsp;
	<span class="action"><a href="http://groups.google.com/group/niwota-info" target="help">Help</a></span>
	</span>
</div>

<!--page content-->
<div id="page-content" >

<div class="section" style="text-align:center; width: 100%; " > 

<div style="margin-top: 128px;">
<span id="error" style="color: #f00;">  </span>
</div>

<div>
<form id="redirectform" action="/" method="post" enctype="application/x-www-form-urlencoded"
	onsubmit="doSubmit(this); return false;">

<span style="color: #fff;">Enter your id or your friend's</span>
<span id="peer_hint" style="font-size: normal;"></span>
<br />

<input name="peer" id="peer" size="32" value="" type="text">

<input name="action" id="action" value="GO" type="submit">

<input name="nonce" id="nonce"  value="" type="hidden">

</form>

<p id="status"></p>
</div>


</div>


</div>
<!--//page content-->

<div id="optionmenu">
<a href="/" title="Home" ><img src="/res/drawable/ic_menu_home.png" alt="" ></a>
<a href="http://groups.google.com/group/niwota-info" title="Help" target="_help"><img src="/res/drawable/ic_menu_help.png" alt="" ></a>
</div>

<div id="footer">Hotweb 1.0.0 &copy; 2010 All rights reserved</div>

<div id="wallpaper" style="display: block;"><img src="http://sites.google.com/site/hotwebagent/hotweb/assets/image/bg_sunrise.jpg" width="100%" height="100%" alt=""></div>

</body>
</html>

